package cn.fancylab.template.web.action.manager.devcie;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.FetchMode;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.jivesoftware.smack.packet.Message;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.eboo.openfire.cmd.sub.GatewayGetConfig;
import com.eboo.openfire.cmd.sub.GatewayLedState;
import com.eboo.openfire.cmd.sub.GatewayLockerState;

import cn.fancylab.model.acl.AuthUser;
import cn.fancylab.model.bs.DeviceController;
import cn.fancylab.model.bs.DeviceGateway;
import cn.fancylab.service.DaoService;
import cn.fancylab.template.untrans.OpenFireService;
import cn.fancylab.template.util.JsonUtil;
import cn.fancylab.template.vo.TableListVo;
import cn.fancylab.template.web.action.admin.BaseAdminController;
import cn.fancylab.web.component.acl.SecurityUtil;
import cn.fancylab.web.support.FancyVelocityView;
import cn.fancylab.web.support.JsonStrDirectOut;
import cn.fancylab.xmpp.magent.MessageListener;

@Controller
public class GatewayController extends BaseAdminController implements InitializingBean {
	@Autowired
	@Qualifier("daoService")
	private DaoService daoService;

	@Autowired
	@Qualifier("openFireService")
	private OpenFireService openFireService;

	@RequestMapping(value = "/manager/device/gateway/list.xhtml")
	public String list(ModelMap model) {
		return "manager/device/gateway/list.vm";
	}

	@RequestMapping(value = "/manager/device/gateway/list_data.xhtml")
	public String list_data(ModelMap model) {
		HttpServletRequest request = getRequest();

		int pagesize = 10;
		int page = 0;
		String currentpage = request.getParameter("page");
		String limit = request.getParameter("limit");
		String identified_no = request.getParameter("identified_no");

		if (StringUtils.isNotBlank(currentpage)) {
			page = Integer.valueOf(currentpage) - 1;
		}
		if (StringUtils.isNotBlank(limit)) {
			pagesize = Integer.valueOf(limit);
		}
		DetachedCriteria query = DetachedCriteria.forClass(DeviceGateway.class);
		query.add(Restrictions.eq("is_del", 0));
		if (StringUtils.isNotBlank(identified_no)) {
			query.add(Restrictions.like("identified_no", "%".concat(identified_no).concat("%")));
		}
		int count = daoService.getObjectCountByCriteria(query);
		query.setFetchMode("deviceController", FetchMode.JOIN);
		query.setProjection(null);
		List<DeviceGateway> list = daoService.findByCriteria(query, page * pagesize, pagesize);

		if (null != list && list.size() > 0) {
			DeviceController deviceController;
			for (DeviceGateway deviceGateway : list) {
				if (deviceGateway.getDeviceController().getUuid() != null) {
					deviceController = daoService.getObject(DeviceController.class,
							deviceGateway.getDeviceController().getUuid());
					if (null != deviceController) {
						deviceGateway.getMap().put("controller_name", deviceController.getController_name());
					}
				}
			}
		}

		TableListVo<DeviceGateway> tableListVo = new TableListVo<DeviceGateway>();
		tableListVo.setCode(0);
		tableListVo.setMsg("");
		tableListVo.setCount(count + "");
		tableListVo.setData(list);

		request.setAttribute(FancyVelocityView.RENDER_JSON, "true");
		request.setAttribute(FancyVelocityView.DIRECT_OUTPUT,
				new JsonStrDirectOut(getResponse(), JsonUtil.serialize(tableListVo)));
		return "common/directOut.vm";
	}

	@RequestMapping(value = "/manager/device/gateway/add.xhtml")
	public String add(String uuid, ModelMap model) {
		return "manager/device/gateway/form.vm";
	}

	@RequestMapping(value = "/manager/device/gateway/edit.xhtml")
	public String edit(String uuid, ModelMap model) {
		DeviceGateway deviceGateway = daoService.getObject(DeviceGateway.class, uuid);
		model.put("deviceGateway", deviceGateway);
		return "manager/device/gateway/form.vm";
	}

	@RequestMapping(value = "/manager/device/gateway/save.xhtml")
	public String save(DeviceGateway deviceGatewayParameter) {
		AuthUser loginUser = SecurityUtil.getLogonUser();

		DeviceGateway deviceGateway = daoService.getObject(DeviceGateway.class, deviceGatewayParameter.getUuid());

		if (null == deviceGateway) {
			deviceGateway = new DeviceGateway();
			deviceGateway.setUuid(UUID.randomUUID().toString());
			deviceGateway.setIs_del(0);
			deviceGateway.setAdd_date(new Date());
			deviceGateway.setAdd_user_id(loginUser.getId());
		} else {
			deviceGateway.setUp_date(new Date());
			deviceGateway.setUp_user_id(loginUser.getId());
		}
		deviceGateway.setGateway_name(deviceGatewayParameter.getGateway_name());
		deviceGateway.setIdentified_no(deviceGatewayParameter.getIdentified_no());
		deviceGateway.setIp_address(deviceGatewayParameter.getIp_address());
		deviceGateway.setRun_state(deviceGatewayParameter.getRun_state());
		deviceGateway.getDeviceController().setUuid(deviceGatewayParameter.getDeviceController().getUuid());

		daoService.saveObject(deviceGateway);

		HttpServletRequest request = getRequest();
		request.setAttribute(FancyVelocityView.RENDER_JSON, "true");
		request.setAttribute(FancyVelocityView.DIRECT_OUTPUT,
				new JsonStrDirectOut(getResponse(), JsonUtil.serialize(deviceGateway)));
		return "common/directOut.vm";
	}

	@RequestMapping(value = "/manager/device/gateway/del.xhtml")
	public String del(String[] uuid) {
		AuthUser loginUser = SecurityUtil.getLogonUser();

		DeviceGateway deviceGateway;
		for (int i = 0, len = uuid.length; i < len; i++) {
			if (StringUtils.isNotBlank(uuid[i])) {
				deviceGateway = daoService.getObject(DeviceGateway.class, uuid[i]);

				if (null != deviceGateway) {
					deviceGateway.setIs_del(1);
					deviceGateway.setDel_date(new Date());
					deviceGateway.setDel_user_id(loginUser.getId());
					daoService.saveObject(deviceGateway);
				}
			}
		}

		HttpServletRequest request = getRequest();
		request.setAttribute(FancyVelocityView.RENDER_JSON, "true");
		request.setAttribute(FancyVelocityView.DIRECT_OUTPUT,
				new JsonStrDirectOut(getResponse(), JsonUtil.serialize(new HashMap())));
		return "common/directOut.vm";
	}

	@RequestMapping(value = "/manager/device/gateway/door.xhtml")
	public String door(String uuid, Boolean state) {
		DeviceGateway deviceGateway = daoService.getObject(DeviceGateway.class, uuid);
		if (null != deviceGateway && deviceGateway.getDeviceController().getUuid() != null) {
			DeviceController deviceController = daoService.getObject(DeviceController.class,
					deviceGateway.getDeviceController().getUuid());
			if (null != deviceController && deviceController.getOpenfire_username() != null) {
				GatewayLockerState gatewayLockerState = new GatewayLockerState();
				gatewayLockerState.setGatewayIdentifiedNo(deviceGateway.getIdentified_no());
				gatewayLockerState.setState(state);

				openFireService.sendMessage(deviceController.getOpenfire_username(),
						JsonUtil.serialize(gatewayLockerState), UUID.randomUUID().toString(), new MessageListener() {

							@Override
							public String processAndGetReply(Message message) {
								System.out.println(message.getBody());
								return null;
							}

						});
			}
		}

		HttpServletRequest request = getRequest();
		request.setAttribute(FancyVelocityView.RENDER_JSON, "true");
		request.setAttribute(FancyVelocityView.DIRECT_OUTPUT,
				new JsonStrDirectOut(getResponse(), JsonUtil.serialize(new HashMap())));
		return "common/directOut.vm";
	}

	@RequestMapping(value = "/manager/device/gateway/gatewayGetConfig.xhtml")
	public String gatewayGetConfig(String uuid, Boolean state) {
		DeviceGateway deviceGateway = daoService.getObject(DeviceGateway.class, uuid);
		if (null != deviceGateway && deviceGateway.getDeviceController().getUuid() != null) {
			DeviceController deviceController = daoService.getObject(DeviceController.class,
					deviceGateway.getDeviceController().getUuid());
			if (null != deviceController && deviceController.getOpenfire_username() != null) {
				GatewayGetConfig gatewayGetConfig = new GatewayGetConfig();
				gatewayGetConfig.setGatewayIdentifiedNo(deviceGateway.getIdentified_no());

				openFireService.sendMessage(deviceController.getOpenfire_username(),
						JsonUtil.serialize(gatewayGetConfig), UUID.randomUUID().toString(), new MessageListener() {

							@Override
							public String processAndGetReply(Message message) {
								System.out.println(message.getBody());
								return null;
							}

						});
			}
		}

		HttpServletRequest request = getRequest();
		request.setAttribute(FancyVelocityView.RENDER_JSON, "true");
		request.setAttribute(FancyVelocityView.DIRECT_OUTPUT,
				new JsonStrDirectOut(getResponse(), JsonUtil.serialize(new HashMap())));
		return "common/directOut.vm";
	}

	@RequestMapping(value = "/manager/device/gateway/led.xhtml")
	public String led(String uuid, Boolean led_state) {
		DeviceGateway deviceGateway = daoService.getObject(DeviceGateway.class, uuid);
		if (null != deviceGateway && deviceGateway.getDeviceController().getUuid() != null) {
			DeviceController deviceController = daoService.getObject(DeviceController.class,
					deviceGateway.getDeviceController().getUuid());
			if (null != deviceController && deviceController.getOpenfire_username() != null) {
				GatewayLedState gatewayLedState = new GatewayLedState();
				gatewayLedState.setGatewayIdentifiedNo(deviceGateway.getIdentified_no());
				gatewayLedState.setLed_state(led_state);

				openFireService.sendMessage(deviceController.getOpenfire_username(),
						JsonUtil.serialize(gatewayLedState), UUID.randomUUID().toString(), new MessageListener() {

							@Override
							public String processAndGetReply(Message message) {
								System.out.println(message.getBody());
								return null;
							}

						});
			}
		}

		HttpServletRequest request = getRequest();
		request.setAttribute(FancyVelocityView.RENDER_JSON, "true");
		request.setAttribute(FancyVelocityView.DIRECT_OUTPUT,
				new JsonStrDirectOut(getResponse(), JsonUtil.serialize(new HashMap())));
		return "common/directOut.vm";
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		// TODO Auto-generated method stub

	}
}
